<template>
  <div>
    <div class="flex items-center justify-between pb-[8px]">
      <el-button type="primary" @click="handleAddProduct">+ 添加商品 </el-button>
      <div class="leading-[20px] text-[14px] text-[#3A4259] mr-[190px]">产品总价：{{ formModel.payment.original_order_currency }} {{ productTotal }}</div>
    </div>
    <vxe-table ref="tableRef" :data="tableData" :round="true" maxHeight="300" border>
      <vxe-column field="order_item_id" title="编号" width="160">
        <template #default="{ row }">
          <el-input v-model="row.order_item_id" placeholder="编号" />
        </template>
      </vxe-column>
      <vxe-column title="图片" width="88">
        <template #default="{ row }">
          <el-image :src="row.main_img" class="w-[68px] h-[68px]" style="border: 0.5px solid #f0f0f0; border-radius: 4px">
            <template #error>
              <img src="~@/assets/images/null-img.png" alt="" />
            </template>
          </el-image>
        </template>
      </vxe-column>
      <vxe-column field="origin_num" title="SKU 自定义SKU" width="160">
        <template #header>
          <div>
            <div>SKU</div>
            <div>自定义SKU</div>
          </div>
        </template>
        <template #default="{ row, rowIndex }">
          <p>{{ row.sku }}</p>
          <p>{{ row.custom_sku }}</p>
          <el-button v-if="!row.sku" type="primary" plain @click="handleAddSku(rowIndex, row)">+ 添加SKU </el-button>
        </template>
      </vxe-column>
      <vxe-column title="渠道SKU*" width="180">
        <template #header>
          <div class="pl-[14px]">ASIN</div>
          <span class="text-[#f56c6c]">*</span> 渠道SKU
        </template>
        <template #default="{ row }">
          <el-tooltip effect="dark" :content="row.asin" placement="top" :disabled="!row.asin">
            <el-select v-model="row.asin" placeholder="请选择" allow-create filterable :disabled="row.skuDisabled" class="mb-[4px] w-[100%]">
              <el-option v-for="item in skuOptions[row.sku] || []" :key="item.label" :label="item.asin" :value="item.asin"> </el-option>
            </el-select>
          </el-tooltip>

          <el-tooltip effect="dark" :content="row.platform_sku" placement="top" :disabled="!row.platform_sku">
            <el-select v-model="row.platform_sku" placeholder="请选择" allow-create filterable :disabled="row.skuDisabled" class="w-[100%]">
              <el-option v-for="item in skuOptions[row.sku] || []" :key="item.label" :label="item.value" :value="item.value"> </el-option>
            </el-select>
          </el-tooltip>
        </template>
      </vxe-column>

      <vxe-column title="平台链接规格" minWidth="160" v-if="tableData.find((v) => v?.ebay_variation_aspects?.length)">
        <template #default="{ row }">
          <div v-for="item in row?.ebay_variation_aspects" :key="item.value">
            <VText title="规格" :value="item.name" :line="1" />
            <VText title="参数" :value="item.value" :line="1" />
          </div>
        </template>
      </vxe-column>

      <vxe-column title="产品名称" field="sku_cn_title" minWidth="140">
        <template #default="{ row }">
          <el-tooltip class="box-item" effect="dark" placement="top">
            <template #content>
              <div style="max-width: 300px">{{ row.sku_cn_title }}</div>
            </template>
            <div class="sku-title">{{ row.sku_cn_title }}</div>
          </el-tooltip>
        </template>
      </vxe-column>
      <vxe-column title="物流属性" field="shipping_logistics_attr" width="80"></vxe-column>
      <vxe-column title="销售数量*" width="90">
        <template #header><span class="text-[#f56c6c]">*</span> 销售数量</template>
        <template #default="{ row, rowIndex }">
          <!-- <el-input-number style="width: 70px" v-model="row.quantity" placeholder="销售数量" :controls="false" :min="1" :precision="0" @change="handleChange(rowIndex, 'quantity')"></el-input-number> -->
          <!-- oninput="value=value.replace(/[^\d]/g, '')" -->
          <el-input v-model="row.quantity" placeholder="销售数量" style="width: 70px" oninput="value=value.replace(/[^\d]/g, '')" @change="handleChange(rowIndex, 'quantity')" />
        </template>
      </vxe-column>
      <vxe-column title="产品单价" width="90">
        <template #default="{ row, rowIndex }">
          <el-input-number
            style="width: 70px"
            v-model="row.original_price"
            placeholder="产品单价"
            :controls="false"
            :min="0"
            :precision="2"
            size="default"
            @change="handleChange(rowIndex)"
            :disabled="(isEdit && formModel.base.build_order_type === 0) || formModel.base.new_order_reason == 6"
          ></el-input-number>
        </template>
      </vxe-column>
      <vxe-column title="产品总价" field="total" width="80"> </vxe-column>
      <vxe-column title="可用库存" field="available_stock" width="80"> </vxe-column>
      <vxe-column title="采购价/RMB" field="purchase_price" width="80">
        <template #header>
          <div>采购价</div>
          /RMB
        </template>
      </vxe-column>
      <vxe-column field="operate" title="操作" width="90">
        <template #default="{ row, rowIndex }">
          <el-link class="mr-2" size="small" type="primary" @click="resetProduct(rowIndex, row)">重置 </el-link>
          <el-link size="small" type="danger" @click="handleDelete(rowIndex)" v-if="!isEdit"> 删除 </el-link>
        </template>
      </vxe-column>
    </vxe-table>
    <SelectProduct v-model:visible="visible" :multiple="multiple" :selectIds="productIds" @uploadSku="handleSku" />
  </div>
</template>

<script setup>
import SelectProduct from "@/components/SelectProduct/index.vue"
import { getChannelSku } from "@/api/public.js"

const props = defineProps({
  skuParams: {
    type: Object,
    default: () => ({}),
  },
  data: {
    type: Object,
    default: () => [],
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  currency: {
    type: String,
    default: "",
  },
  formModel: {
    type: Object,
    default: () => {},
  },
})

const emit = defineEmits(["addSku", "changInput"])

const tableRef = ref([])
const tableData = ref([])
const skuOptions = ref({})
const data = reactive({
  visible: false,
  multiple: false,
  rowIndex: "",
})

const { visible, multiple, rowIndex } = toRefs(data)

watch(
  () => tableData.value,
  (val) => {
    if (val && val.length > 0) {
      getSkuList(val.map((n) => n.sku))
    }
  }
)

watch(
  () => props.data,
  (val) => {
    if (val && val.length) {
      tableData.value = val.map((n) => ({ ...n, total: n.original_price * n.quantity, skuDisabled: true })) // TODO bigNumber
    }
  }
)

const handleAddSku = (index, row) => {
  rowIndex.value = index
  multiple.value = false
  visible.value = true
  emit("addSku", index)
}

const resetProduct = (index, _row) => {
  // platform_sku
  const row = {
    ..._row,
    main_img: "",
    sku: "",
    custom_sku: "",
    // platform_sku: '',
    sku_cn_title: "",
    shipping_logistics_attr: "",
    available_stock: "",
    purchase_price: "",
  }
  tableData.value[index] = Object.assign({}, row)
  nextTick(() => {
    tableRef?.value.reloadData(tableData.value)
  })
}

const productTotal = computed(() => {
  let total = tableData.value.reduce((pre, n) => pre + (n.total || 0), 0).toFixed(2)
  emit("changInput", { key: "orderAmount", value: total })
  return total
})

const productIds = computed(() => {
  return tableData.value.map((n) => n.sku)
})

const handleDelete = (index) => {
  tableData.value.splice(index, 1)
}

const getSkuList = async (skuList) => {
  const { shop_id, platform } = props.skuParams || {}
  try {
    const { data } =
      (await getChannelSku({
        goods_sku_list: skuList,
        shop_id: shop_id,
        platform,
      })) || {}
    if (!platform) return

    const newData = data.map((n) => ({
      ...n,
      label: n.platform_sku,
      value: n.platform_sku,
    }))
    const newOptions = newData.reduce((acc, curr) => {
      let key = curr.goods_sku
      if (!acc[key]) {
        acc[key] = []
      }
      acc[key].push(curr)
      return acc
    }, {})
    skuOptions.value = newOptions

    tableData.value.forEach((item) => {
      if (!item.platform_sku) {
        if (!newOptions?.[item.sku]?.length) {
          item.platform_sku = item.sku
        } else if (newOptions?.[item.sku]?.length == 1) {
          item.platform_sku = newOptions[item.sku]?.[0].value
        }
      }
    })
  } catch (e) {
    console.error(e)
  }
}

const handleChange = (i, key = "") => {
  if (key == "quantity") {
    if (tableData.value[i].quantity == 0) {
      tableData.value[i].quantity = 1
    }
  }
  const { original_price = 0, quantity = 0, total = 0 } = tableData.value[i]
  let row = {
    ...tableData.value[i],
    rowIndex: i,
  }
  if (key == "quantity") {
    row.original_price = Number((total / quantity).toFixed(2))
  } else {
    row.total = Number((original_price * quantity).toFixed(2))
  }

  tableData.value[i] = Object.assign({}, row)

  nextTick(() => {
    tableRef?.value.reloadData(tableData.value)
  })
}

const handleAddProduct = () => {
  multiple.value = true
  visible.value = true
}

const generateRandomNumber = () => {
  let randomNumber = Math.floor(Math.random() * 100000)
  return String(randomNumber).padStart(5, "0")
}

const handleSku = (e) => {
  const isMultiple = multiple.value
  console.error("eeee", e, isMultiple)
  if (isMultiple) {
    const _list = e.map((n, idx) => ({
      order_item_id: generateRandomNumber(),
      main_img: n.attr_img,
      sku: n.sku,
      custom_sku: n.custom_sku,
      sku_cn_title: n.sku_cn_title,
      shipping_logistics_attr: n.shipping_logistics_attr || "-",
      quantity: 1,
      original_amount: 0,
      available_stock: 0,
      purchase_price: n.purchase_price,
      platform_sku: "",
      original_price: 0,
      total: 0,
    }))
    tableData.value = [...tableData.value, ..._list]
  } else {
    const { attr_img, sku, id, custom_sku, sku_cn_title, logistics_attributes_name, purchase_price } = e
    tableData.value[rowIndex.value] = JSON.parse(
      JSON.stringify({
        ...tableData.value[rowIndex.value],
        main_img: attr_img,
        sku,
        custom_sku,
        sku_cn_title,
        shipping_logistics_attr: logistics_attributes_name || "-",
        // quantity: 0,
        // price: 0,
        available_stock: 0,
        purchase_price,
        // original_price:0,
      })
    )
    nextTick(() => {
      tableRef?.value.reloadData(tableData.value)
    })
  }
}

const getTableData = () => {
  return tableRef?.value.getTableData()
}

defineExpose({ getTableData })
</script>

<style lang="scss" scoped>
.sku-title {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
}
</style>
